package com.zusmart.core.condition.extend;

import java.util.Map;
import java.util.Map.Entry;

import com.zusmart.base.util.StringUtils;
import com.zusmart.core.bean.BeanDefinition;
import com.zusmart.core.condition.Condition;
import com.zusmart.core.condition.ConditionContext;
import com.zusmart.core.config.ConfigSourceManager;
import com.zusmart.core.plugin.PluginManager;

public class ConditionalOnHasBeanRule implements Condition {

	@Override
	public boolean matches(ConditionContext conditionContext, Map<String, BeanDefinition> beanDefinitions, BeanDefinition targetBeanDefinition, PluginManager pluginManager, ConfigSourceManager configSourceManager) {
		ConditionalOnHasBean hasBean = (ConditionalOnHasBean) conditionContext.getExtendAnnotation();
		String value = hasBean.value();
		Class<?> clazz = hasBean.clazz().equals(Void.class) ? null : hasBean.clazz();
		return this.doMatches(conditionContext, beanDefinitions, targetBeanDefinition, value, clazz);
	}

	protected boolean doMatches(ConditionContext conditionContext, Map<String, BeanDefinition> beanDefinitions, BeanDefinition targetBeanDefinition, String value, Class<?> clazz) {
		// 默认的两个条件未设置,忽略当前注解功能,直接返回true,不做任何屏蔽
		if (StringUtils.isBlank(value) && null == clazz) {
			return true;
		}
		if (StringUtils.isBlank(value) && null != clazz) {// 名称为空,类型不为空
			for (Entry<String, BeanDefinition> entry : beanDefinitions.entrySet()) {
				if (entry.getValue().isAssignable(clazz)) {
					return true;// 找到同类型的允许Bean注册
				}
			}
			return false;// 否则不允许Bean注册
		} else if (StringUtils.isNotBlank(value) && null == clazz) {
			return beanDefinitions.containsKey(value);// 名称不为空,类型为空,直接判断名称是否存在
		} else {
			// 名称类型都不为空,判断名称和类型同时匹配
			if (beanDefinitions.containsKey(value) && beanDefinitions.get(value).isAssignable(clazz)) {
				return true;
			}
			return false;
		}
	}

}